import { Component } from '@angular/core';

import { Events, AlertController, App, List, ModalController, NavController, NavParams, ActionSheetController } from 'ionic-angular';

import { EmailDetailService } from './detail.service';

import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

import { Config } from '../../../providers/config';

import { EmailSendPage } from '../send/send.component';

import { Common } from '../../../providers/common';

import { Storage } from '@ionic/storage';

import _ from 'lodash';

@Component({
  selector: 'page-email-detail',
  templateUrl: './detail.html',
  providers: [EmailDetailService]
})
export class EmailDetailPage {
	moa_page_name: any = "page-email-detail";
  moa_page_explain: any = "邮件详情";

  id = "";
  type = "";
  email: any = {
    refenDtos: [{}],
    readflag: 0
  };

  // 收件人列表
  recieveList = {
    isShow: false,
    list: []
  };
  // 密送人列表
  secretList = {
    isShow: false,
    list: []
  };
  // 抄送人列表
  otherList = {
    isShow: false,
    list: []
  };

  // 限制展示多少人，才收起来
  showListLimit = 5;

  _ = _;

  alertTips = "";

  operateType = "";

  emname = "";

  sendUserInfo: any = {};

  domContent: any = "";
  domTitle: any = "";

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    private sanitizer: DomSanitizer,
    public detailService: EmailDetailService,
    private navParams: NavParams,
    public actionSheetCtrl: ActionSheetController,
    public common: Common,
    public events: Events,
    public storage: Storage,
    public config: Config
  ) {
    let that = this;
    this.id = this.navParams.get('id');
    this.type = this.navParams.get('type');
    this.storage.get('userInfo').then(function(userInfo) {
      that.emname = userInfo.emname;
      that.loadData();
    });
  }

  loadData() {
    let that = this;
    this.detailService.getDetailData(this.id, this.type).subscribe(data => {
      if (data) {
        this.email = data;
        console.info(data.content);
        this.domTitle = data.bostitle;
        this.domTitle = this.sanitizer.bypassSecurityTrustHtml(this.domTitle);
        // 格式化图片链接
        this.common.tranformImgLik(this.email.content, true).then(function(formatContent) {
          that.email.content = formatContent;
          that.domContent = that.sanitizer.bypassSecurityTrustHtml(that.email.content);
          // 绑定html
          that.common.bindLinkersEvent("page-email-detail");
        });
        this.recieveList.list = data.recievname ? data.recievname.split(',') : [];
        this.secretList.list = data.secretname ? data.secretname.split(',') : [];
        this.otherList.list = data.othername ? data.othername.split(',') : [];
        // 如果是发件箱，则显示
        if (this.type == 'IMOutbox') {
          // 判断，如果密送是否只有自己
        } else if (_.indexOf(this.secretList.list, this.emname) > -1) {
          this.secretList.list = [this.emname];
        } else {
          this.secretList.list = [];
        }
        console.info(this.email);
        if (this.recieveList.list.length <= this.showListLimit) {
          this.recieveList.isShow = true;
        }
        if (this.secretList.list.length <= this.showListLimit) {
          this.secretList.isShow = true;
        }
        if (this.otherList.list.length <= this.showListLimit) {
          this.otherList.isShow = true;
        }

        // 先请求发件人信息
        this.detailService.getContactDetailByLoginid(this.email.sendaccount).subscribe(data => {
          this.sendUserInfo = data;
          console.info('发件人信息：');
          console.info(this.sendUserInfo);
          if (this.email.readflag == 0) {
            // 更新邮件为已阅
            this.detailService.updateMailInfoStat(this.email.mailbosid, { readflag: 1 }, false).subscribe(data => {
            });
            // isreceipt只有在收件箱打开，并且是需要回执
            if (this.email.isreceipt == 1 && this.type == 'IMailInbox') {
              // 回执邮件
              this.detailService.sendEmail({
                bostitle: "已读：" + this.email.bostitle,
                content: "这是邮件收条，收件人：<br/>" + this.emname + "<br/>原邮件主题：" + this.email.bostitle + "<br/>此收条表明收件人的手机上曾显示过此邮件。",
                isreceipt: 0,
                login: "",
                otherlist: "",
                recievelist: this.sendUserInfo.deptStr,
                secretlist: "",
                urgency: 9
              }).subscribe(data => {
              });
            }
          }
        });

      }
    });
  }
  // 更新邮件状态
  updateMailInfoStat(params) {
    this.detailService.updateMailInfoStat(this.id, params, true).subscribe(data => {
      this.email = _.assignIn(this.email, params);
      if (this.operateType == 'delete') {
        this.events.publish('email-list:delete', this.id);
        this.navCtrl.pop();
      }
      let alert = this.alertCtrl.create({
        title: '提示',
        subTitle: this.alertTips,
        "buttons": ['确认']
      });
      alert.present();
    });
  };

  openFile(id, name) {
    console.info('-----openFile-----' + id);
    this.common.openFile('email', 'normal', id, name, false);
  };

  editEmail(type) {
    console.info('---type----');
    console.info(type);
    let orgContent = '发送时间：' + this.email.sendtime + '<br/>' +
      '发件人：' + this.email.refenDtos[0].svalue + '<br/>' +
      '收件人：' + this.email.recievname + '<br/>';

    if (this.email.othername) {
      orgContent = orgContent + '抄送人：' + this.email.othername + '<br/>';
    }
    orgContent = orgContent + '主题：' + this.email.bostitle + '<br/><br/>';
    orgContent = orgContent + this.email.content + '<br/>';
    let e: any = {}
    e.isreceipt = this.email.isreceipt;
    e.urgency = this.email.urgency;
    e.readflag = this.email.readflag;
    e.attach = this.email.attach;
    console.info(this.email);
    console.info(this.sendUserInfo);
    if (this.sendUserInfo) {
      if (type === 'forward') {
        e.bostitle = "转发：" + this.email.bostitle;
        e.content = "<br/><br/><br/>" + orgContent;
        e.opType = 'forward';
      } else if (type === 'reply') {
        e.bostitle = "回复：" + this.email.bostitle;
        e.recievelist = this.sendUserInfo.deptStr;
        e.recievname = this.sendUserInfo.emname;
      } else if (type === 'reply_all') {
        e.bostitle = "回复：" + this.email.bostitle;
        e.recievelist = this.email.recievelist;
        e.recievname = this.email.recievname;
        e.otherlist = this.email.otherlist;
        e.othername = this.email.othername;
      } else if (type === 'reply_with_content') {
        e.bostitle = "回复：" + this.email.bostitle;
        e.content = "<br/><br/><br/>" + orgContent;
        e.recievelist = this.sendUserInfo.deptStr;
        e.recievname = this.sendUserInfo.emname;
      } else if (type === 'reply_all_with_content') {
        e.bostitle = "回复：" + this.email.bostitle;
        e.content = "<br/><br/><br/>" + orgContent;
        e.recievelist = this.email.recievelist;
        e.recievname = this.email.recievname;
        e.otherlist = this.email.otherlist;
        e.othername = this.email.othername;
      }

      if (e.recievelist && e.recievelist.indexOf(this.sendUserInfo.empid) === -1) {
        e.recievelist = this.sendUserInfo.deptStr + ',' + e.recievelist;
        e.recievname = this.sendUserInfo.emname + ',' + e.recievname;
      }

      this.navCtrl.push(EmailSendPage, e);
    }

  };

  deleteEmail(isTrueDelete?) {
    let that = this;
    this.operateType = 'delete';
    // 如果为重要邮件，不能删除
    if (this.email.urgency == 1 && this.type == 'IMailInbox') {
      let alert = this.alertCtrl.create({
        title: '提示',
        subTitle: '该邮件为重要邮件，不能删除',
        "buttons": ['确认']
      });
      alert.present();
      // 如果该邮件为待办邮件不能删除
    } else if (this.email.status == 6 && this.type == 'IMailInbox') {
      let alert = this.alertCtrl.create({
        title: '提示',
        subTitle: '该邮件为待办邮件，不能删除',
        "buttons": ['确认']
      });
      alert.present();
    } else {
      let prompt = this.alertCtrl.create({
        title: '提示',
        message: "确认是否删除该邮件？",
        buttons: [
          {
            text: '取消',
            handler: data => {
              console.log('Cancel clicked');
            }
          },
          {
            text: '确认',
            handler: data => {
              that._deleteEmail(isTrueDelete);
            }
          }
        ]
      });
      prompt.present();
    }
  }

  /**
   * [_deleteEmail 执行删除邮件操作]
   * @param {Boolean} isTrueDelete [description]
   */
  _deleteEmail(isTrueDelete?) {
    if (isTrueDelete || this.type === 'WasteBox') {
      this.detailService.deleteEmail(this.id, this.type).subscribe(data => {
        if (data) {
          this.events.publish('email-list:delete', this.id);
          let alert = this.alertCtrl.create({
            title: '提示',
            subTitle: '永久删除成功',
            "buttons": ['确认']
          });
          alert.present();
          this.navCtrl.pop();
        }
      });
    } else {
      // 如果该邮件为待办邮件
      if (this.type === 'IMailTask') {
        this.alertTips = '删除待办邮件成功';
        this.updateMailInfoStat({ status: 2 });
      } else if (this.type === 'IMailImp') {
        // 如果该邮件为重要邮件
        this.alertTips = '删除重要邮件成功';
        this.updateMailInfoStat({ urgency: 2 });
      } else {
        this.alertTips = '删除到废件箱成功';
        this.updateMailInfoStat({ status: 3 });
      }
    }
  }

  /**
   * [moveBackToInbox 废件箱恢复至收件箱]
   */
  moveBackToInbox() {
    this.operateType = 'delete';
    this.alertTips = '恢复至收件箱成功';
    this.updateMailInfoStat({ status: 2 });
  }

  /**
   * [HisMailToInbox 恢复历史邮件到收件箱]
   */
  HisMailToInbox() {
    this.operateType = 'delete';
    this.detailService.HisMailToInbox(this.id).subscribe(data => {
      this.events.publish('email-list:delete', this.id);
      this.navCtrl.pop();
      let alert = this.alertCtrl.create({
        title: '提示',
        subTitle: '恢复至收件箱成功',
        "buttons": ['确认']
      });
      alert.present();
    });
  }

  chooseListType() {
    let bottons = [];
    // 注意！！请勿更改数组顺序！
    let full_bottons = [{
      id: 0,
      text: '转发',
      handler: () => {
        this.editEmail('forward');
      }
    }, {
      id: 1,
      text: '回复',
      handler: () => {
        this.editEmail('reply');
      }
    }, {
      id: 2,
      text: '回复所有人',
      handler: () => {
        this.editEmail('reply_all');
      }
    }, {
      id: 3,
      text: '回复（带原文）',
      handler: () => {
        this.editEmail('reply_with_content');
      }
    }, {
      id: 4,
      text: '回复所有人（带原文）',
      handler: () => {
        this.editEmail('reply_all_with_content');
      }
    }, {
      id: 5,
      text: '设为重要邮件',
      handler: () => {
        this.operateType = 'update';
        this.alertTips = '设置为重要邮件成功';
        this.updateMailInfoStat({ urgency: 1 });
      }
    }, {
      id: 6,
      text: '设为待办',
      handler: () => {
        this.operateType = 'update';
        this.alertTips = '设置为待办邮件成功';
        this.updateMailInfoStat({ status: 6 });
      }
    }, {
      id: 7,
      text: '删除',
      role: 'destructive',
      handler: () => {
        this.deleteEmail();
      }
    }, {
      id: 8,
      text: '永久删除',
      role: 'destructive',
      handler: () => {
        this.alertTips = '永久删除邮件成功';
        this.deleteEmail(true);
      }
    }, {
      id: 9,
      text: '移至收件箱',
      handler: () => {
        this.moveBackToInbox();
      }
    }, {
      id: 10,
      text: '恢复',
      handler: () => {
        this.alertTips = '恢复至收件箱成功';
        this.HisMailToInbox();
      }
    }];

    // 如果是收件箱详情
    if (this.type == 'IMailInbox') {
      bottons = full_bottons;
      // 不能删
      bottons.pop();
      bottons.pop();
    }
    // 如果是发件箱
    if (this.type == 'IMOutbox') {
      bottons.push(full_bottons[0]);
      bottons.push(full_bottons[8]);
    }

    // 如果是废件箱
    if (this.type == 'WasteBox') {
      bottons.push(full_bottons[8]);
      bottons.push(full_bottons[9]);
    }

    // 如果是待办列表 或者 重要邮件
    if (this.type == 'IMailTask' || this.type == 'IMailImp') {
      bottons.push(full_bottons[0]);
      bottons.push(full_bottons[7]);
    }

    // 如果是历史邮件
    if (this.type == 'IMailHIS') {
      bottons.push(full_bottons[8]);
      bottons.push(full_bottons[10]);
    }

    bottons.push({
      text: '取消',
      role: 'cancel',
      handler: () => {

      }
    });
    let actionSheet = this.actionSheetCtrl.create({
      title: '',
      buttons: bottons
    });
    actionSheet.present();
  };

  changeShowList(list) {
    list.isShow = !list.isShow;
  }

  ionViewDidLoad() {
    // this.app.setTitle('EmailDetail');
  }

}
